package com.apes.fn.fico.expenseType;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("expenseTypeService")
public class ExpenseTypeService extends DomainService {

    @Autowired
    ExpenseTypeRepository expenseTypeRepository;

    /***
     * 创建
     * @param request
     * @return
     */
    public ExpenseType create(SimpleRequest request) {
        ExpenseType expenseType = request.getO(ExpenseType.class);

        return expenseTypeRepository.saveAndFlush(expenseType);
    }

    /***
     * 更新
     * @param request
     * @return
     */
    public ExpenseType update(SimpleRequest request) {
        isVaild(request, expenseTypeRepository);

        ExpenseType expenseType = request.getO(ExpenseType.class);

        return expenseTypeRepository.saveAndFlush(expenseType);

    }

    /***
     * 删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        isVaild(request, expenseTypeRepository);
        ExpenseType expenseType = request.getO(ExpenseType.class);

        expenseTypeRepository.delete(expenseType);
        return "删除成功";
    }


    /***
     * 数据是否合法
     * @param request
     * @param repository
     */
    private Model isVaild(SimpleRequest request, CustomRepository repository) {
        Model oldModel = (Model) repository.findOne((String) request.get("id"));
        if (oldModel == null) throw new RuntimeException("单据【" + request.get("id") + "】在系统中不存在。");
        if (oldModel.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return oldModel;
    }



}
